import CompList from '@/views/component-list';
import type { IOriginMenuItem } from '@code4x/types';
import { BlankPage } from '@code4x/layout';
import type { RouteRecordRaw } from 'vue-router';

/**
 * 构造路由表和菜单树
 * @param list
 * @returns
 */
export function genRoutesAndMenus(list: IOriginMenuItem[]) {
  const flatted: IOriginMenuItem[] = [];
  const flatFunc = (list: IOriginMenuItem[]) => {
    Array.isArray(list) &&
      list.forEach((el) => {
        flatted.push(el);
        Array.isArray(el.children) && flatFunc(el.children);
      });
  };
  flatFunc(list);
  const mapFunc = (list: IOriginMenuItem[]): RouteRecordRaw[] => {
    if (Array.isArray(list)) {
      return list.map(
        ({
          title,
          code,
          type,
          icon,
          hidden,
          target = '_self',
          keepalive = false,
          menuId,
          url,
          redirect,
          pid,
        }) => {
          const component =
            type === 2 && code && CompList[code]
              ? CompList[code]
              : markRaw(() => BlankPage);
          return {
            path: url,
            name: code,
            redirect,
            component,
            meta: {
              title,
              type,
              icon: icon as string,
              id: menuId as string,
              hidden,
              keepalive,
              target,
              pid,
            },
            children: [],
          };
        },
      );
    }
    return [];
  };
  const permission = mapFunc(flatted);
  return {
    flatted,
    permission,
  };
}
